package com.lvyq.myplayer.util

/**
 * 文件描述：downloadMp3UsingOkHttp
 * 作者：lvyq
 * 创建时间：2025-04-16
 * 修改时间：2025-04-16
 */
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

fun downloadMp3UsingOkHttp(fileUrl: String, destinationPath: String) {
    val client = OkHttpClient()

    val request = Request.Builder()
        .url(fileUrl)
        .build()

    client.newCall(request).execute().use { response ->
        if (!response.isSuccessful) throw IOException("Unexpected code $response")

        response.body?.byteStream()?.use { inputStream ->
            val outputStream = FileOutputStream(File(destinationPath))
            val buffer = ByteArray(1024)
            var bytesRead: Int
            while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                outputStream.write(buffer, 0, bytesRead)
            }
            outputStream.close()
            println("Download completed: $destinationPath")
        }
    }
}

fun main() {
    val fileUrl = "https://sharefs.tx.kugou.com/202504161543/a75a2f57871295913aaa9528276acf66/v3/d9aa8e91e1bac2714c38a5ac72230a73/yp/full/ap1000_us0_pi409_s3427134537.mp3"
    val destinationPath = "sample.mp3"
    downloadMp3UsingOkHttp(fileUrl, destinationPath)
}